import React, { useEffect, useState, useRef } from 'react';
import TweenOne from 'rc-tween-one';
import { Menu, Button } from 'antd';
import { getChildrenToRender } from '@/util/utils';
const { Item, SubMenu } = Menu;
import { useRouter } from 'next/router';
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
import { ReactSVG } from 'react-svg';
import ApplyForm from "@/pages/h5/introduce";

const Header = ({ dataSource, isMobile,...props }) => {
  const router = useRouter();
  let location = '//sfsscn.com';
  const [phoneOpen, setPhoneOpen] = useState(undefined);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [isHideHorizonMenu, setIsHideHorizonMenu] = useState(false);
  const h5Component = useRef();

  const navData = dataSource.Menu.children;

  const goPage = (item) => {
    if (isHideHorizonMenu && !phoneOpen) {
      return false
    }
    if (!item.disabled) {
      window.location.href = `${publicRuntimeConfig.basePath + item.href}`;
    }
    //router.push(path);
  }

  const resizeUpdate = () => {
    const isHideHorizon = window.innerWidth < 1100;
    setIsHideHorizonMenu(isHideHorizon);
  }

  useEffect(() => {
    const path = window.location.pathname.replace(publicRuntimeConfig.basePath,'');
    const subMenuMap = {
      '/case/smartRetail':`${publicRuntimeConfig.basePath + '/case'}`,
      '/case/smartPark':`${publicRuntimeConfig.basePath + '/case'}`,
      '/':`${publicRuntimeConfig.basePath + '/home'}`,
    }
    const selectedKey = subMenuMap[path] ? subMenuMap[path] : window.location.pathname;
    setSelectedKeys(selectedKey);
    //监听窗口
    resizeUpdate();
    window.addEventListener('resize', resizeUpdate);
    return () => {
      // 组件销毁时移除监听事件
      window.removeEventListener('resize', resizeUpdate);
    }
  }, [])

  const navChildren = navData.map((item) => {
    const { children: a, subItem, ...itemProps } = item;
    const path = `${publicRuntimeConfig.basePath + item.path}`;
    if (subItem) {
      return (
        <SubMenu
          key={path}
          {...itemProps}
          title={(
            <a
              key={path}
              className={`header0-item-block ${a.className}`.trim()}
            >
              {a.children[0].children}
            </a>
          )}
        >
          {subItem.map(($item, i) => {
            const { children: childItem } = $item;
            const subPath = `${publicRuntimeConfig.basePath + $item.path}`;
            return (
              <Item key={subPath} {...$item}>
                <div className={`menu-icon-container ${childItem.children[0].disabled ? 'disabled':''}`}>
                  <ReactSVG 
                    className='svg-icon'
                    src={childItem.children[0].icon}
                  />
                  <a onClick={() => {goPage(childItem.children[0])}} className='header0-item-block'>
                    {childItem.children[0].title}
                  </a>
                </div>
              </Item>
            );
          })}
        </SubMenu>
      );
    }
    return (
      <Item key={path} {...itemProps}>
        <a onClick={() => {goPage(a)}} className={`header0-item-block ${a.className}`.trim()}>
          {a.children.map(getChildrenToRender)}
        </a>
      </Item>
    );
  });
  
  const phoneClick = () => {
    setPhoneOpen(!phoneOpen);
  };

  const menuOnSelect = ({ key }) => {
    setSelectedKeys(key);
  }

  const redirectToLogin = () => {

    if (/(ext)|(vue)|(sf-express)|(sit)/.test(window.location.host)) {
      location = '//extdata.sit.sf-express.com';
    }
    // window.location.href = `${location}/#/login/sigin`;
    window.open(`${location}/#/login/sigin`, '_blank')
  }

  const apply = () => {
    const anchorName = 'Footer0_1'
    // 找到锚点
    let anchorElement = document.getElementById(anchorName);
    // 如果对应id的锚点存在，就跳转到锚点
    if (anchorElement) { anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' }) };
  }

  const openApplyForm = () => {
    h5Component.current.goApply();
  }

  const goIndexPage = () => {
    window.location.href = `/`;
  }

  const moment = phoneOpen === undefined ? 300 : null;
  return (
    <div {...dataSource.wrapper} {...props}>
      <div className={`${dataSource.page.className}${phoneOpen ? ' open' : ''}`}>
        <div className={dataSource.logo.className}>
          <img className='pic' src={dataSource.logo.children} alt="img" onClick={goIndexPage}/>
        </div>
        <div className='phone-apply-button' onClick={openApplyForm}>
          <span>申请试用</span>
        </div>
        {isHideHorizonMenu && (
          <div
            {...dataSource.mobileMenu}
            onClick={() => {
              phoneClick();
            }}
          >
            <em />
            <em />
            <em />
          </div>
        )}
        <TweenOne
          {...dataSource.Menu}
          animation={
            isHideHorizonMenu
              ? {
                height: 0,
                duration: 300,
                onComplete: (e) => {
                  e.target.style.height = 'auto';
                  // if (phoneOpen) {
                  //   e.target.style.height = 'auto';
                  // }
                },
                ease: 'easeInOutQuad',
              }
              : null
          }
          moment={moment}
          reverse={!!phoneOpen}
        >
          <Menu
            mode={isHideHorizonMenu ? 'inline' : 'horizontal'}
            selectedKeys={[selectedKeys]}
            onClick={menuOnSelect}
            theme="dark"
          >
            {navChildren}
          </Menu>
        </TweenOne>
        <div className={dataSource.button.className}>
          <a href="#register">
            <Button type="primary">
              申请试用
            </Button>
          </a>
          <Button onClick={redirectToLogin} type="primary">
            登录
          </Button>
        </div>
      </div>
      <ApplyForm ref={h5Component} hideMainPage/>
    </div>
  );
};

export default Header;
